<template>
	<view>
		<view class="wrapper bgw">
			<view class="blank20"></view>
			<view class="flex" style="align-items: baseline;">
				<!-- <view class="">
					显示：
				</view> -->
				<view class="flex-1">
					<u-checkbox-group v-model="fn_list" placement="row"  @change="checkboxChange">
						<view class="flex" style="flex-wrap: wrap;">
							<template v-for="v in fn_config">
								<view class="" style="margin: 15upx;">
									
									<u-checkbox activeColor="#675f91" :label="v" :name="v" :disabled="true" v-if="v=='食材'"></u-checkbox>
									<u-checkbox activeColor="#675f91" :label="v" :name="v" v-else></u-checkbox>
								</view>
							</template>
						</view>
					</u-checkbox-group>
					<view class="blank20"></view>
					<view class="flex">
						<!-- <view class="flex-1 ">
							<u-button text="刷新" type="primary" @click="toExcel" size="small"></u-button>
						</view> -->
						<!-- <view class="ml10 mr10"></view> -->
						<view class="flex-1 ">
							<u-button text="下载Excel" type="success" @click="toExcel" :disabled="!excelUrl" size="small"></u-button>
						</view>
						<view class="ml10 mr10"></view>
						<view class="flex-1">
							<u-button text="下载图片" type="primary" id="downloadBtn" size="small"></u-button>
						</view>
					</view>
				</view>
			</view>
			<view class="blank20"></view>
		</view>
		<view class="blank20"></view>
		<view class="" id="poster" ref="poster">
			<view class="bgw">
				<view class="blank20"></view>
				<view class="text-center font-bold">
					{{date}}
				</view>
				<view class="blank20"></view>
			</view>
			<view class="bg-gray">
				<view class="flex">
					<view class="flex-1 col-item" :class="v=='食材'?'':'text-center'" v-for="v in fn_list">
						{{v}}
					</view>
				</view>
			</view>
			<view class="bgw">
				<template v-for="v in vals_list">
					<view class="flex">
						<view class="flex-1 col-item" :class="key=='食材'?'':'text-center'" v-for="key in fn_list">
							{{v[key]}}
						</view>
					</view>
					<u-line dashed></u-line>
				</template>
			</view>
		</view>

		<!-- <u-gap height="73"></u-gap>
		<view class="fixed-bottom wrapper bgw">
			<u-line></u-line>
			<u-gap height="16" bgColor="#ffffff"></u-gap>
			
			<u-gap height="16" bgColor="#ffffff"></u-gap>
		</view> -->

	</view>
</template>

<script>
	import config from '@/common/config';
	import html2canvas from 'html2canvas';
	import {
		base64ToPath
	} from 'image-tools';
	import {
		share_po
	} from '@/common/api.js';
	// const Binding = uni.requireNativePlugin('bindingx');
	export default {
		data() {
			return {
				date: '',
				ids: [],
				fn_list: [],
				vals_list: [],
				loadingStatus: '',
				excelUrl: '',
				fn_config:['食材','数量','单位','单价','供应商','金额']

			}
		},
		methods: {
			checkboxChange(e){
				this.setFnListStorage(e);
			},
			setFnListStorage(fn_list){
				uni.setStorage({
					key: 'purchaseShareFnList',
					data: fn_list,
					success: function() {}
				});
			},
			receiveRenderData(data) {
				// console.log(data);
				let that = this;
				uni.hideLoading();
				base64ToPath(data, '.jpeg').then(function(imgPath) {
					// console.log(imgPath);
					// #ifdef H5   
					//H5生效
					uni.downloadFile({
						url: imgPath,
						success: (res) => {
							let link = document.createElement('a');
							link.href = imgPath;
							link.download = '采购信息.png';
							// link.download = imgPath.replace(/(.*\/)*([^.]+.*)/ig,"$2").split("?")[0];
							link.click();
						},
						fail: err => {
							console.log('保存失败' + `:`, err);
						}
					})
					// #endif
					// #ifdef APP-PLUS
					//APP-PLUS生效
					uni.share({
						provider: "weixin",
						scene: "WXSceneSession",
						type: 2,
						imageUrl: imgPath,
						success: function(res) {
							console.log("success:" + JSON.stringify(res));
						},
						fail: function(err) {
							console.log("fail:" + JSON.stringify(err));
						}
					});
					uni.saveImageToPhotosAlbum({
						filePath: imgPath,
						success: function() {
							uni.showModal({
								content: "保存成功，请到相册查看",
								showCancel: false,
							});

						},
						fail: err => {
							console.log('保存失败' + `:`, err);
							that.$u.toast('保存失败');
						}
					});
					// #endif
				})

			},
			openLoading() {
				uni.showLoading({
					title: '保存相册中...'
				})
			},
			pageScrollTo() {
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 0
				})
			},
			getData() {
				let fnListStorage = false;
				try {
					fnListStorage = uni.getStorageSync('purchaseShareFnList') || false;
				} catch (e) {}
				
				uni.showLoading({
					title: '加载中'
				});
				this.loadingStatus = 'loading';
				share_po({
					po_ids_list: this.ids,
					format: 'png'
				}).then((res) => {
					let vals_list = res.result['图片'].vals_list
					if(!fnListStorage){
						this.fn_list = res.result['图片'].fn_list;
						this.setFnListStorage(this.fn_list);
					}else{
						this.fn_list = fnListStorage;
					}
					vals_list.forEach(v=>{
						for(let key in v){
							if(typeof v[key] == 'number'){
								v[key] = this.formatPrice(v[key]);
							}
						}
					})
					this.vals_list = vals_list;

					let url = res.result.url;
					this.excelUrl = config.webUrl + url

					this.loadingStatus = 'end';
				}).catch(() => {

				}).finally(() => {
					uni.hideLoading();
					uni.stopPullDownRefresh();
				})
			},
			toExcel() {
				let that = this;
				let url = this.excelUrl;
				// #ifdef APP-PLUS
				//APP-PLUS生效
				uni.share({
					provider: "weixin",
					scene: "WXSceneSession",
					type: 0,
					href: url,
					title: "分享采购Excel",
					imageUrl: "https://vkceyugu.cdn.bspapp.com/VKCEYUGU-uni-app-doc/d8590190-4f28-11eb-b680-7980c8a877b8.png",
					success(res) {
						console.log("success:" + JSON.stringify(res));
					},
					fail(err) {
						that.$u.toast('分享失败');
						console.log("fail:" + JSON.stringify(err));
					}
				});
				// #endif
				// uni.downloadFile({
				// 	url: url,
				// 	success: function(res) {
				// 		var filePath = res.tempFilePath;
				// 		uni.openDocument({
				// 			filePath: filePath,
				// 			showMenu: true,
				// 			success: function(res) {
				// 				console.log('打开文档成功');
				// 			}
				// 		});
				// 	}
				// });
			}

		},
		onLoad(d) {
			this.date = d.date || '2020-10-10'
			if (!d.ids) {
				d.ids = '8,6,7';
			}
			let ids = d.ids.split(',');
			ids.forEach(v => {
				this.ids.push(Number(v));
			})
			// console.log(ids);
			// this.ids = [43];
			this.getData();

		},
		onShow() {

		},
		onReady() {

		},
		onShareAppMessage(res) {
			let ids = this.ids.join(',');
			return {
				title: '采购信息',
				path: '/pagesA/purchaseShare/purchaseShare?date=' + this.date + '&ids=' + ids
			}
		}
	}
</script>

<script module="renderScript" lang="renderjs">
	import html2canvas from 'html2canvas';
	import {
		base64ToPath
	} from 'image-tools';
	import Vue from 'vue'
	// console.log(document.querySelector('#app'));
	export default {
		mounted() {
			// console.log(process.env.NODE_ENV);

			document.querySelector('#downloadBtn').onclick = ((e) => {
				this.exportPhoto2(e);
			})
			// this.exportPhoto();
		},
		methods: {
			exportPhoto(e, ownerVm) {
				ownerVm.callMethod('openLoading')
				var dom = document.querySelector('#poster'); // 获取dom元素
				html2canvas(dom, {
					width: dom.clientWidth, //dom 原始宽度
					height: dom.clientHeight,
					scrollY: 0,
					scrollX: 0,
					useCORS: true, //支持跨域，但好像没什么用
				}).then((canvas) => {
					// 将生产的canvas转为base64
					var base64 = canvas.toDataURL('image/png')
					// 将数据回调给第一个script
					ownerVm.callMethod('receiveRenderData', base64)
				}).catch((e) => {
					console.log(e);
				});
			},
			exportPhoto2(e, ownerInstance) {
				// ownerVm.callMethod('openLoading')
				var dom = document.querySelector('#poster'); // 获取dom元素
				html2canvas(dom, {
					width: dom.clientWidth, //dom 原始宽度
					height: dom.clientHeight,
					scrollY: 0,
					scrollX: 0,
					useCORS: true, //支持跨域，但好像没什么用
				}).then((canvas) => {
					// 将生产的canvas转为base64
					var base64 = canvas.toDataURL('image/png');
					this.$ownerInstance.callMethod('receiveRenderData', base64)
				}).catch((e) => {
					console.log(e);
				});
			}
		}
	}
</script>

<style>
	.col-item {
		padding: 15upx 20upx;
	}
</style>